package up7.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    private Map<String, FileItem> m_items;

    public HttpRequest(PageContext pc) throws FileUploadException {
        this.m_items = new HashMap<String,FileItem>();
        HttpServletRequest r = (HttpServletRequest) pc.getRequest();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List files = upload.parseRequest(r);
        Iterator it = files.iterator();

        while(it.hasNext())
        {
            FileItem item = (FileItem) it.next();
            this.m_items.put(item.getFieldName(),item);
        }
    }

    public String getString(String name)
    {
        if(this.m_items.containsKey(name))
        {
            return this.m_items.get(name).getString();
        }
        return "";
    }

    public FileItem getFile(String name)
    {
        if(this.m_items.containsKey(name))
        {
            return this.m_items.get(name);
        }
        return null;
    }

}
